/**
 * 
 */
package com.oda.camera;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.client.HttpClient;

import com.activity.colza.R;
import com.oda.camera.UploadService.ServiceHandler;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

/**
 * @author zou
 *
 */
public class SendService extends Service{
	/**
	 * L'url to upload picture
	 */
	private static final String url="";
	
	/**
	 * Request proprety
	 */
	private String delimiter = "--";
	private String boundary =  "SwA"+Long.toString(System.currentTimeMillis())+"SwA";
	private OutputStream os;
	String lineEnd = "\r\n";
	
	/**
	 * The connection
	 * @author zou
	 *
	 */
	private HttpURLConnection con;
	
	

	private Intent mInvokeIntent;
	private volatile Looper mUploadLooper;
	private volatile ServiceHandler mUploadHandler;
	private int check = 0;
	
	public final class ServiceHandler extends Handler{
		public ServiceHandler(Looper looper) {
			super(looper);
		}

		/**
		 * Handle the message	
		 */
		public void handleMessage(Message msg) {
			//get extra datas
			Uri selectedImg = (Uri)msg.obj;
			Log.i(getClass().getSimpleName(),"selectedImg =" + selectedImg);

			//upload the file to the web server
			//doHttpUpload(selectedImg);

			Log.i(getClass().getSimpleName(), "Message: " + msg);
			Log.i(getClass().getSimpleName(), "Done with #" + msg.arg1);
			stopSelf(msg.arg1);
		}
	};

	//Method called when (an instance of) the Service is created
	public void onCreate() {
		Log.d("Create","Service create");
		Log.i(getClass().getSimpleName(),"HttpUploader on create");

		// This is who should be launched if the user selects our persistent
		// notification.
		mInvokeIntent = new Intent();
		mInvokeIntent.setClassName("com.oda.camera", "SendService");

		// Start up the thread running the service. Note that we create a
		// separate thread because the service normally runs in the process's
		// main thread, which we don't want to block.
		HandlerThread thread = new HandlerThread("SendService");
		thread.start();

		mUploadLooper = thread.getLooper();
		mUploadHandler = new ServiceHandler(mUploadLooper);
	}

	public void onStart(Intent uploadintent, int startId) {
		Log.d("Start", "Service start");
		// recup des data pour envoi via msg dans la msgqueue pour traitement
		Message msg = mUploadHandler.obtainMessage();
		msg.arg1 = startId;
		//on place l'uri reçu dans l'intent dans le msg pour le handler
		msg.obj = uploadintent.getData();
		mUploadHandler.sendMessage(msg);
		Log.d(getClass().getSimpleName(), "Sending: " + msg);

	}

	/**
	 * Begin manage upload
	 */
	public void connectForMultipart() throws Exception {
		con = (HttpURLConnection) ( new URL(url)).openConnection();
		con.setRequestMethod("POST");
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
		con.connect();
		os = con.getOutputStream();
	}
	
	public void addFormPart(String paramName, String value) throws Exception {
		writeParamData(paramName, value);
	}
	
	private void writeParamData(String paramName,String value) throws Exception {
		os.write( (delimiter + boundary + "\r\n").getBytes());
		os.write( "Content-Type: text/plain\r\n".getBytes());
		os.write( ("Content-Disposition: form-data; name=\"" + paramName + "\"\r\n").getBytes());
		os.write( ("\r\n" + value + "\r\n").getBytes());
	}

	public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
	    os.write( (delimiter + boundary + "\r\n").getBytes());
	    os.write( ("Content-Disposition: form-data; name=\"" + paramName +  "\"; filename=\"" + fileName + "\"\r\n"  ).getBytes());
	    os.write( ("Content-Type: application/octet-stream\r\n"  ).getBytes());
	    os.write( ("Content-Transfer-Encoding: binary\r\n"  ).getBytes());
	    os.write("\r\n".getBytes());	    
	    os.write(data);	     
	    os.write("\r\n".getBytes());
	}
	
	
	public void uploadData(){
		String url = "url";
        String param1 = "firsparam";
        String param2 = "secondparam";
        Bitmap b = BitmapFactory.decodeResource(this.getResources(), R.drawable.logo_woda);
         
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        b.compress(CompressFormat.JPEG, 0, baos);
 
//        try {
//            HttpClient client = new HttpClient(url);
//            client.connectForMultipart();
//            client.addFormPart("param1", param1);
//            client.addFormPart("param2", param2);
//            client.addFilePart("file", "logo.png", baos.toByteArray());
//            client.finishMultipart();
//            String data = client.getResponse();
//        }
//        catch(Throwable t) {
//            t.printStackTrace();
//        }
	}

	/**
	 * Ending manage upload
	 */


	// Method called when the (instance of) the Service is requested to terminate
	public void onDestroy() {
		mUploadLooper.quit();

		if(check == 0) { //http response contains no error
			Toast.makeText(SendService.this, "photo envoyée", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(SendService.this, "échec d'envoi de la photo", Toast.LENGTH_SHORT).show();
		}
		super.onDestroy();
	}
	/* (non-Javadoc)
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
